package com.itheima.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AdminLoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获得请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //放行不需要登录就可以访问的路径
        String path = request.getURI().getPath();
        log.debug("请求的地址：{}", path);
        if (path.startsWith("/admin/login")) {
            return chain.filter(exchange);
        }
        //获得请求头中的token
        String token = request.getHeaders().getFirst("token");
        //如果有token（记得非空判断）
        if (StringUtils.isNotEmpty(token)) {
            //就检验token的有效性
            int verifyToken = AppJwtUtil.verifyToken(token);
            //如果有效就放行
            if (SystemConstants.JWT_OK == verifyToken) {
                return chain.filter(exchange);
            }
        }
        //如果都没有放行，就返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //结束
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
